﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace OnlyleHttpModel
{
    public class CompressWhitespaceModule : IHttpModule 
    {

        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest); 
        }

        private void context_BeginRequest(object sender, EventArgs e)
        {
            //HttpApplication app = sender as HttpApplication;
            //#region 过滤不需要压缩
            //if (app.Request.RawUrl.ToLower().Contains(".js"))
            //{
            //    return;
            //}
            //else if (app.Request.RawUrl.ToLower().Contains(".ico"))
            //{
            //    return;
            //}
            //else if (app.Request.RawUrl.ToLower().Contains(".css"))
            //{
            //    return;
            //}
            //else if (app.Request.RawUrl.ToLower().Contains(".png"))
            //{
            //    return;
            //}
            //else if (app.Request.RawUrl.ToLower().Contains(".jpeg"))
            //{
            //    return;
            //}
            //else if (app.Request.RawUrl.ToLower().Contains(".jpg"))
            //{
            //    return;
            //}
            //else if (app.Request.RawUrl.ToLower().Contains(".gif"))
            //{
            //    return;
            //}
            //else if (app.Request.RawUrl.ToLower().Contains(".swf"))
            //{
            //    return;
            //}
            //#endregion
            //CompressWhitespace(app);
        }

        private static void CompressWhitespace(HttpApplication app)
        {
            HttpContext context = app.Context;
            HttpRequest request = context.Request;
            string acceptEncoding = request.Headers["Accept-Encoding"];
            HttpResponse response = context.Response;
            if (!string.IsNullOrEmpty(acceptEncoding))
            {
                acceptEncoding = acceptEncoding.ToUpperInvariant();
                if (acceptEncoding.Contains("GZIP"))
                {
                    response.Filter = new CompressWhitespaceFilter(context.Response.Filter, CompressOptions.GZip);
                    response.AppendHeader("Content-encoding", "gzip");
                }
                else if (acceptEncoding.Contains("DEFLATE"))
                {
                    response.Filter = new CompressWhitespaceFilter(context.Response.Filter, CompressOptions.Deflate);
                    response.AppendHeader("Content-encoding", "deflate");
                }
            }
            response.Cache.VaryByHeaders["Accept-Encoding"] = true;
        }
    }
}
